from _decimal import Decimal

from django.shortcuts import render

# Create your views here.
from rest_framework.generics import CreateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from django_redis import get_redis_connection

from goods.models import SKU
from orders.serializers import OrderSettlementSerializer, OrderCommitSerializer

"""订单结算"""


class OrderSettlementView(APIView):
    """
    # 1.进入订单结算的一定是认证用户
    # 1.1 获取用户信息
    # 2.连接reids,获取redis里cart的数据
    # 3.获取redis里selected的数据
    # 4.取出reids里勾选的商品,生成一个新的字典
    # 5.根据商品id获取商品信息
    # 6.设置运费
    # 7.将订单信息进行序列化
    """
    # 1.进入订单结算的一定是认证用户
    permission_classes = [IsAuthenticated]

    def get(self, request):
        # 1.1 获取用户信息
        user = request.user
        # 2.连接reids,获取redis里cart的数据
        redis_conn = get_redis_connection('cart')
        redis_cart = redis_conn.hgetall('cart_%s' % user.id)
        # 3.获取redis里selected的数据
        redis_selected = redis_conn.smembers('cart_selected_%s' % user.id)
        # 4.取出reids里勾选的商品,生成一个新的字典
        cart = {}
        for sku_id in redis_selected:
            cart[int(sku_id)] = int(redis_cart[sku_id])
        # 5.根据商品id获取所有商品信息,以及商品数量
        skus = SKU.objects.filter(id__in=cart.keys())
        for sku in skus:
            sku.count = cart[sku.id]
        # 6.设置运费
        freight = Decimal('10.00')

        # 7.将订单信息进行序列化
        serializer = OrderSettlementSerializer({"freight": freight, "skus": skus})
        return Response(serializer.data)



class OrderView(CreateAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = OrderCommitSerializer